package com.briup.jd2407cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.jd2407cms.domain.Article;
import com.briup.jd2407cms.domain.Category;
import com.briup.jd2407cms.domain.extend.ArticleExtend;
import com.briup.jd2407cms.exception.ServiceException;
import com.briup.jd2407cms.result.ResultCode;
import com.briup.jd2407cms.service.ArticleService;
import com.briup.jd2407cms.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
    implements ArticleService{

    @Autowired
    ArticleMapper articleMapper;

    @Override
    public List<Article> getArticleByCategoryId(Integer categoryId) {
        return articleMapper.selectList(new LambdaQueryWrapper<Article>().eq(Article::getCategoryId,categoryId));
    }

    @Override
    @Transactional
    public void saveOrUpdateArticle(Article article) {
        if(article.getId() == null){
            article.setPublishTime(LocalDateTime.now());
            save(article);
        }else {
            updateById(article);
        }
    }

    @Override
    public void changeArticleStatus(Long id, String status) {
        Article article = new Article();
        article.setId(id);
        article.setStatus(status);
        updateById(article);
    }

    @Override
    public void deleteArticleBatch(List<Long> ids) {
        // 删除文章，先正常删除，等到评论模块写了代码之后
        // 删除文章要先删除下面的评论
        if(ids == null || ids.isEmpty()){
            throw new ServiceException(ResultCode.FAIL);
        }
        if(ids.size() == 1){
            removeById(ids.get(0));
        }else {
            removeByIds(ids);
        }
    }

    @Override
    public ArticleExtend getArticleDetailById(Long id) {
        return articleMapper.selectDetailById(id);
    }

    @Override
    public IPage<ArticleExtend> getAllByConditionByPage(Integer pageNum, Integer pageSize, String name, String status, Integer categoryId, Long userId, Integer charged, LocalDateTime begin, LocalDateTime end) {
        // 分页
        IPage<ArticleExtend> page = new Page<>(pageNum,pageSize);
        return articleMapper.selectAllByCondition(page, name, status, categoryId, userId, charged, begin, end);
    }
}




